package com.cn.security.service;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cn.mapper.SysPermissionMapper;
import com.cn.mapper.SysUserMapper;
import com.cn.pojo.SysPermission;
import com.cn.pojo.SysUser;
import com.cn.security.entity.LogUser;
import com.cn.web.service.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义验证登录
 */

@Component
public class MyAuthenticationProvider implements AuthenticationProvider {



    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysPermissionMapper sysPermissionMapper;



    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String presentedPassword = (String)authentication.getCredentials();
        UserDetails userDeatils = null;
        // 根据用户名获取用户信息
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<SysUser> userLambdaQueryWrapper = wrapper.eq(SysUser::getAccount, username);
        SysUser sysUser = sysUserMapper.selectOne(userLambdaQueryWrapper);
        if (StringUtils.isEmpty(sysUser)) {
            throw new BadCredentialsException("用户名不存在");
        } else {
            userDeatils = new User(username, sysUser.getPassword(), AuthorityUtils.commaSeparatedStringToAuthorityList("USER"));
            //判断密码是否正确
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            boolean matches = bCryptPasswordEncoder.matches(presentedPassword,sysUser.getPassword());
            if (!matches){
                throw new RuntimeException("密码错误");
            }

            List<String> permissionsList = new ArrayList<>();

            if (sysUser != null) {
                //获取该用户所拥有的权限
                List<SysPermission> sysPermissions = sysPermissionMapper.selectPermissionList(sysUser.getUserId());

                // 声明用户授权
                sysPermissions.forEach(sysPermission -> {
                    permissionsList.add(sysPermission.getPermissionCode());
                });
            }

            UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(userDeatils, authentication.getCredentials(), userDeatils.getAuthorities());
            result.setDetails(new LogUser(sysUser,permissionsList));
            return result;
        }
}

    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }
}